package com.qiantu.phone.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.entity.UserInfoBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.BuildConfig;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.manager.OBSManager;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.dialog.BottomAvatarDialog;
import com.qiantu.phone.ui.dialog.BottomDistrictDialog;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.ui.dialog.BottomTimeDialog;
import com.lxj.xpopup.XPopup;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class PersonalDataActivity extends AppActivity {

    private ImageView imageAvatar;
    private SettingBar mNameView;
    private SettingBar mAddressView;
    private SettingBar mSexView;
    private SettingBar mBirthDayView;
    private BottomEditDialog mBottomEditDialog;
    private BottomAvatarDialog mBottomAvatarDialog;
    private BottomListDialog mBottomListDialog;
    private BottomTimeDialog mBottomTimeDialog;
    private BottomDistrictDialog mBottomDistrictDialog;

    private UserInfoBean userInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.personal_data_activity;
    }

    @Override
    protected void initView() {
        imageAvatar = findViewById(R.id.user_image);
        mNameView = findViewById(R.id.sb_person_data_name);
        mSexView = findViewById(R.id.sb_person_data_sex);
        mBirthDayView = findViewById(R.id.sb_person_data_birthday);
        mAddressView = findViewById(R.id.sb_person_data_address);
        setOnClickListener(imageAvatar, mNameView, mSexView, mBirthDayView, mAddressView);
    }

    @Override
    protected void initData() {
        userInfo = AppApplication.getInstance().getLoginInfo().getUserInfo();
        if (userInfo != null) {
            updateView();
        }

        LLHttpManager.getUserInfo(this, new HttpCallback<HttpData<UserInfoBean>>(this){
            @Override
            public void onSucceed(HttpData<UserInfoBean> result) {
                super.onSucceed(result);
                userInfo = result.getData();
                updateView();
                AppApplication.getInstance().getLoginInfo().setUserInfo(userInfo);
                AppApplication.getInstance().updateLoginInfo(AppApplication.getInstance().getLoginInfo());
            }
        });
    }

    private void updateView(){
        if(userInfo == null){
            return;
        }
        GlideApp.with(getActivity())
                .load(userInfo.getAvatar())
                .placeholder(imageAvatar.getDrawable())
                .error(imageAvatar.getDrawable())
                .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                .into(imageAvatar);
        mNameView.setRightText(userInfo.getNickName());
        mSexView.setRightText(userInfo.getGenderStr(getContext()));
        mBirthDayView.setRightText(userInfo.getBirthday());
        String district = userInfo.getProvince() + " " + userInfo.getCity() + " " + userInfo.getDistrict();
        mAddressView.setRightText(district);
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        if (view == imageAvatar) {
            showBottomAvatarDialog();
        } else if (view == mNameView) {
            showBottomEditDialog(mNameView.getRightText().toString());
        } else if (view == mSexView) {
            showBottomListDialog();
        } else if (view == mBirthDayView) {
            showBottomTimeDialog();
        } else if (view == mAddressView) {
            showBottomDistrictDialog();
        }
    }

    private void showBottomDistrictDialog() {
        if (mBottomDistrictDialog == null) {
            mBottomDistrictDialog = new BottomDistrictDialog(this);
            mBottomDistrictDialog.setDialogClickListener(new BottomDistrictDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(String text, String code) {
                    mAddressView.setRightText(text);
                    mBottomDistrictDialog.dismiss();
                    String[] districts = text.split(" ");
                    userInfo.setProvince(districts[0]);
                    userInfo.setCity(districts[1]);
                    userInfo.setDistrict(districts[2]);
                    modify();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomDistrictDialog);
        }
        mBottomDistrictDialog.setSelectedItem(userInfo.getProvince(), userInfo.getCity(), userInfo.getDistrict());
        mBottomDistrictDialog.show();
    }

    private void showBottomListDialog() {
        if (mBottomListDialog == null) {
            mBottomListDialog = new BottomListDialog(this);
            mBottomListDialog.setDialogClickListener(new BottomListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(this);
            List<String> data = new ArrayList<>();
            data.add(getString(R.string.ll_man));
            data.add(getString(R.string.ll_woman));
            data.add(getString(R.string.ll_secret));
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    String genderName = listLabelAdapter.getSelected();
                    mSexView.setRightText(genderName);
                    mBottomListDialog.dismiss();
                    userInfo.setGender(getString(R.string.ll_man).equals(genderName) ? "1" : "2");
                    modify();
                }
            });
            mBottomListDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomListDialog);
        }
        ListLabelAdapter listLabelAdapter = (ListLabelAdapter) mBottomListDialog.getAdapter();
        listLabelAdapter.setSelected(mSexView.getRightText().toString());
        mBottomListDialog.show();
    }

    private void showBottomTimeDialog() {
        if (mBottomTimeDialog == null) {
            mBottomTimeDialog = new BottomTimeDialog(this);
            mBottomTimeDialog.setDialogClickListener(new BottomTimeDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(String time) {
                    mBirthDayView.setRightText(time);
                    mBottomTimeDialog.dismiss();
                    userInfo.setBirthday(time);
                    modify();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomTimeDialog);
        }
        mBottomTimeDialog.setSelectDate(userInfo.getBirthday());
        mBottomTimeDialog.show();
    }

    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    mNameView.setRightText(mBottomEditDialog.getText());
                    userInfo.setNickName(mBottomEditDialog.getText());
                    modify();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setLabel(getString(R.string.nick_name_modify));
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.NICKNAME_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private void showBottomAvatarDialog() {
        if (mBottomAvatarDialog == null) {
            mBottomAvatarDialog = new BottomAvatarDialog(this);
            mBottomAvatarDialog.setDialogClickListener(new BottomAvatarDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(int selected) {
                    switch (selected) {
                        case 1:
                            imageAvatar.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.img_me_avatar_male1));
                            userInfo.setAvatar(BuildConfig.APP_AVATAR_BASE + "img_me_avatar_male1.png");
                            break;
                        case 2:
                            imageAvatar.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.img_me_avatar_male2));
                            userInfo.setAvatar(BuildConfig.APP_AVATAR_BASE + "img_me_avatar_male2.png");
                            break;
                        case 3:
                            imageAvatar.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.img_me_avatar_girl1));
                            userInfo.setAvatar(BuildConfig.APP_AVATAR_BASE + "img_me_avatar_girl1.png");
                            break;
                        case 4:
                            imageAvatar.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.img_me_avatar_girl2));
                            userInfo.setAvatar(BuildConfig.APP_AVATAR_BASE + "img_me_avatar_girl2.png");
                            break;
                    }
                    modify();
                }

                @Override
                public void onStartCamera() {
                    mBottomAvatarDialog.dismiss();
                    getImage(SelectImageActivity.ACTION_CAMERA);
                }

                @Override
                public void onStartGallery() {
                    mBottomAvatarDialog.dismiss();
                    getImage(SelectImageActivity.ACTION_GALLERY);
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomAvatarDialog);
        }
        mBottomAvatarDialog.show();
    }

    /**
     * 上传裁剪后的图片
     */
    private void updateCropImage(File file, boolean deleteFile) {
        if (file == null) return;
        showDialog();
        String path = String.format("avatar/default/avatar-%s-%d.jpg",userInfo.getPhone(),System.currentTimeMillis());
        OBSManager.updateImage(path, file, new OBSManager.OBSCallBack() {
            @Override
            public void onSuccess(String imgUrl) {
                if (imgUrl!=null){
                    GlideApp.with(getActivity())
                            .load(imgUrl)
                            .placeholder(imageAvatar.getDrawable())
                            .error(imageAvatar.getDrawable())
                            .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                            .into(imageAvatar);
                    userInfo.setAvatar(imgUrl);
                    modify();
                    hideDialog();
                    if (deleteFile) {
                        file.delete();
                    }
                }
            }

            @Override
            public void onFail() {
                hideDialog();
            }
        });
    }

    private void modify() {
        if (TextUtils.isEmpty(userInfo.getGender())) {
            toast(R.string.please_select_gender);
            return;
        }
        if (TextUtils.isEmpty(userInfo.getBirthday())) {
            toast(R.string.please_select_birthday);
            return;
        }
        if (TextUtils.isEmpty(userInfo.getAvatar())) {
            toast(R.string.please_select_avatar);
            return;
        }
        // 隐藏软键盘
        hideKeyboard(getCurrentFocus());
        LLHttpManager.editBasicInfo(this, userInfo, new HttpCallback<HttpData<Void>>(this) {
            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }

            @Override
            public void onSucceed(HttpData<Void> data) {
                if (data.isRequestSucceed()) {
                    AppApplication.getInstance().getLoginInfo().setUserInfo(userInfo);
                    AppApplication.getInstance().updateLoginInfo(AppApplication.getInstance().getLoginInfo());
                    toast(R.string.reset_success);
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        });
    }

    private XXPermissions xxPermissions;
    private String currentAction; // 添加成员变量保存当前action
    
    private void getImage(String action) {
        currentAction = action; // 保存当前action
        if(xxPermissions == null){
            xxPermissions = XXPermissions.with(this);
        }
        String[] permissions;
        String permissionHint;
        
        if(SelectImageActivity.ACTION_CAMERA.equals(action)) {
            // 拍照只需要相机权限
            permissions = new String[]{Manifest.permission.CAMERA};
            permissionHint = "App需要使用您的相机权限，来拍摄头像图片。如若已拒绝，再使用本功能前请先前往手机设置中将本应用的相机权限改为允许。";
        } else {
            // 相册选择需要存储权限
            permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            permissionHint = "App需要使用您的存储权限，来选择相册中的图片作为头像。如若已拒绝，再使用本功能前请先前往手机设置中将本应用的存储权限改为允许。";
        }
        
        if(!XXPermissions.isGranted(getContext(),permissions) && AppApplication.isHuawei() ){
            showConfirmHintDialog(permissionHint, action);
        }else{
            requestPermission(action, permissions);
        }
    }

    private void actionProfilePic(String action) {
        Intent intent = new Intent(this, SelectImageActivity.class);
        intent.setAction(SelectImageActivity.ACTION_SQUARE);
        intent.putExtra("ACTION", action);
        startActivityForResult(intent, new OnActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, @Nullable Intent data) {
                if (data!=null && data.getExtras()!=null){
                    //在这里获得了剪裁后的Bitmap对象，可以用于上传
                    String imagePath = data.getExtras().getString(SelectImageActivity.CROP_IMAGE_PATH);
                    updateCropImage(new File(imagePath), true);
                }
            }
        });
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;

    private void showConfirmHintDialog(String text,String action) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            // 用户取消，不做任何操作
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            String[] permissions;
                            if(SelectImageActivity.ACTION_CAMERA.equals(currentAction)) {
                                permissions = new String[]{Manifest.permission.CAMERA};
                            } else {
                                permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                            }
                            requestPermission(currentAction, permissions);
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setCancelable(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void requestPermission(String action, String[] permissions) {
        if (permissions == null || permissions.length == 0) {
            actionProfilePic(action);
        } else {
            xxPermissions.permission(permissions)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            if(all){
                                actionProfilePic(action);
                            }
                        }
                        @Override
                        public void onDenied(List<String> permissions, boolean never) {
                            ToastUtils.show(R.string.common_permission_fail_1);
                        }

                    });
        }
    }
}